package com.carkeeper.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carkeeper.exception.BussinessException;
import com.carkeeper.mapper.ServiceSubtypeMapper;
import com.carkeeper.pojo.ServiceSubtypePO;
import com.carkeeper.service.ServiceSubTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class ServiceSubTypeServiceImpl implements ServiceSubTypeService {
    @Autowired
    private ServiceSubtypeMapper serviceSubtypeMapper;

    @Override
    public Page<ServiceSubtypePO> queryPage(Long parentId, Long page, Long pageSize, String code, String name) {
        Page<ServiceSubtypePO> poPage = new Page<>(page, pageSize);
        QueryWrapper<ServiceSubtypePO> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(code)) {
            queryWrapper.like("code", code);
        }
        if (!StringUtils.isEmpty(name)) {
            queryWrapper.like("name", name);
        }
        if (parentId != null || parentId > 0) {
            queryWrapper.eq("parent_id", parentId);
        }

        Page<ServiceSubtypePO> serviceSubType = serviceSubtypeMapper.selectPage(poPage, queryWrapper);

        return serviceSubType;
    }

    @Override
    public ServiceSubtypePO query(long id) {
        ServiceSubtypePO query = serviceSubtypeMapper.selectById(id);

        return query;
    }

    @Override
    public void add(ServiceSubtypePO serviceSubtypePO) {
        if (StringUtils.isEmpty(serviceSubtypePO.getCode())) {
            throw new BussinessException("分类编码字段不能为空");
        }
        QueryWrapper<ServiceSubtypePO> wrapper = new QueryWrapper<>();
        wrapper
                .lambda()
                .eq(ServiceSubtypePO::getCode, serviceSubtypePO.getCode());
        Integer count = serviceSubtypeMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BussinessException("该分类编码已经存在");
        }
        serviceSubtypeMapper.insert(serviceSubtypePO);
    }

    @Override
    public void update(long id, ServiceSubtypePO serviceSubtypePO) {
        QueryWrapper<ServiceSubtypePO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        serviceSubtypeMapper.update(serviceSubtypePO, queryWrapper);
    }

    @Override
    public void delete(long serviceSubtypeById) {
        serviceSubtypeMapper.deleteById(serviceSubtypeById);
    }

    @Override
    public List<ServiceSubtypePO> findAll() {
        LambdaQueryWrapper<ServiceSubtypePO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        return serviceSubtypeMapper.selectList(lambdaQueryWrapper);
    }
}



